﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Tenancy.Helper;
using SQLServer.DBUtility;
using System.Text.RegularExpressions;
using System.Data;

namespace Tenancy.Server
{
    /// <summary>
    /// Hbung_Register 的摘要说明
    /// </summary>
    public class Hbung_Register : IHttpHandler
    {
        /// <summary>
        /// 租赁注册接口
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //用户注册的手机号
            string Hbung_Phone = context.Request.Params["Tel"];
            string HB_Tel = string.Empty;
            if (string.IsNullOrEmpty(Hbung_Phone))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Tel为空"));
            }
            else
            {
                HB_Tel = DESEncrypt.MD5Decrypt(Regex.Replace(Hbung_Phone.Trim(), @"\s", "+"));
                string pattern = "^1[0-9]{10}$"; //正则表达式字符串
                Regex cgsregex = new Regex(pattern);
                bool isMatch = cgsregex.IsMatch(HB_Tel);
                if (!isMatch)
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Tel格式不正确"));
                    return;
                }
            }
            //签名
            string HBsign = context.Request.Params["Sign"];
            if (string.IsNullOrEmpty(HBsign))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Sign为空"));
                return;
            }
            else
            {
                if (GenerClass.IsOkMatch(HB_Tel) != Regex.Replace(HBsign.Trim(), @"\s", "+"))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Sign不匹配"));
                    return;
                }
            }

            //方法名字 0 1
            string Hbung_Meth = context.Request.Params["Meth"];
            if (string.IsNullOrEmpty(Hbung_Meth))
            {
                context.Response.Write(GenerClass.SetParamErrorJsData("Meth为空"));
                return;
            }
            else
            {
                if (Hbung_Meth != "0" && Hbung_Meth != "1")
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Meth格式不正确"));
                    return;
                }
            }
            //验证码
            string Hbung_CodeNum = context.Request.Params["CodeNum"];
            //获取验证码
            if (Hbung_Meth == "0")
            {
                if (!GenerClass.TelISNORepeat(HB_Tel))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Tel已注册过"));
                    return;
                }
                //随机生成六位数
                string SixNum = GenerClass.CreateNum();
                string VilateStr = string.Format("insert into Hbung_ValidateCode  (vCode,vTel,vType,vTime,Status) values ('{0}','{1}',1,getdate(),'1') ", SixNum, HB_Tel);
                if (DBHelpSQL.ExecuteSql(VilateStr) > 0)
                {
                    string msgcgs = "[{\"CodeNum\": \"" + SixNum + "\" }]";
                    context.Response.Write(GenerClass.SetSucessJsData("发送成功", msgcgs));
                    //此处发送验证码到手机
                    string Strmsg = "【利星行机械】注册验证码：" + SixNum + "感谢你的注册。";
                    Tenancy.Helper.MsgSend.HB_SendMsg(HB_Tel, Strmsg);
                }
                else
                {
                    context.Response.Write(GenerClass.SetChangeErrorJsData("获取验证码失败"));
                    return;
                }
            }
            //注册用户
            if (Hbung_Meth == "1")
            {

                if (!GenerClass.TelISNORepeat(HB_Tel))
                {
                    context.Response.Write(GenerClass.SetParamErrorJsData("Tel已注册过"));
                    return;
                }

                if (string.IsNullOrEmpty(Hbung_CodeNum))
                {
                    context.Response.Write(GenerClass.SetChangeErrorJsData("CodeNum为空"));
                    return;
                }

                else
                {
                    string HB_ValiCode = string.Format("select * from Hbung_ValidateCode where vCode='{0}' and vTel='{1}' and vType='1' ", Hbung_CodeNum, HB_Tel);
                    DataTable HB_CodeDate = DBHelpSQL.Query(HB_ValiCode).Tables[0];
                    if (HB_CodeDate != null && HB_CodeDate.Rows.Count > 0)
                    {
                        string comna = string.Empty;//公司名字
                        string compho = string.Empty;//公司电话
                        string comaddress = string.Empty;//公司地址
                        string comspeo = string.Empty;//服务人员
                        string ZCData = string.Format(" select CTel,SID,SName,SSex,SMobile,SName,CAddress,CName from View_CustomerForSaleman  where RegisterMobilephone='{0}'", Hbung_Phone);
                        DataTable Zcda = DbLocalSQL.Query(ZCData).Tables[0];
                        if (Zcda != null && Zcda.Rows.Count > 0)
                        {
                            comna = Zcda.Rows[0]["CName"].ToString();
                            compho = Zcda.Rows[0]["CTel"].ToString();
                            comaddress = Zcda.Rows[0]["CAddress"].ToString();
                            comspeo = Zcda.Rows[0]["SName"].ToString();
                        }
                        List<string> sqls = new List<string>();
                        string HB_InStr = string.Format(@"insert into Hbung_CompanyInfo (CellTel,CraeatTime,CompanyName,Phone,Address,ServicePerson) values
                        ('{0}',getdate(),'{1}','{2}','{3}','{4}') ", HB_Tel, comna, compho, comaddress, comspeo);
                        sqls.Add(HB_InStr);
                        HB_InStr = string.Format("update Hbung_ValidateCode set Status='0' where vCode='{0}' and vTel='{1}' and vType='1' ", Hbung_CodeNum, HB_Tel);
                        sqls.Add(HB_InStr);
                        if (DBHelpSQL.ExecuteSqlTran(sqls) > 0)
                        {
                            string HB_CgsStr = string.Format("select * from Hbung_CompanyInfo where CellTel='{0}'", HB_Tel);
                            DataTable HB_ComInfo = DBHelpSQL.Query(HB_CgsStr).Tables[0];
                            if (HB_ComInfo != null && HB_ComInfo.Rows.Count > 0)
                            {
                                string SDFSTr = string.Format(" select CTel,SID,SName,SSex,SMobile,SName,CAddress,CName from View_CustomerForSaleman  where RegisterMobilephone='{0}'", Hbung_Phone);
                                DataTable SDFSTrData = DbLocalSQL.Query(SDFSTr).Tables[0];

                                if (SDFSTrData != null && SDFSTrData.Rows.Count > 0)
                                {
                                    HB_ComInfo.Columns.Add("CTel", typeof(string));
                                    HB_ComInfo.Rows[0]["CTel"] = SDFSTrData.Rows[0][0];

                                    HB_ComInfo.Columns.Add("SID", typeof(int));
                                    HB_ComInfo.Rows[0]["SID"] = SDFSTrData.Rows[0][1];

                                    HB_ComInfo.Columns.Add("SName", typeof(string));
                                    HB_ComInfo.Rows[0]["SName"] = SDFSTrData.Rows[0][2];

                                    HB_ComInfo.Columns.Add("SSex", typeof(string));
                                    HB_ComInfo.Rows[0]["SSex"] = SDFSTrData.Rows[0][3];

                                    HB_ComInfo.Columns.Add("SMobile", typeof(string));
                                    HB_ComInfo.Rows[0]["SMobile"] = SDFSTrData.Rows[0][4];
                              
                                }
                                string Hb_DateJson = JsonHelper.DataTableToJSON(HB_ComInfo);
                                context.Response.Write(GenerClass.SetSucessJsData("注册成功", Hb_DateJson));
                            }
                            else
                            {
                                context.Response.Write(GenerClass.SetChangeErrorJsData("注册失败"));
                                return;
                            }
                        }
                        else
                        {
                            context.Response.Write(GenerClass.SetChangeErrorJsData("与获取验证码的手机号不同"));
                            return;
                        }
                    }
                }
            }
        }
     
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}